# coding=utf-8
"""
作者：董新强 
创建时间：2020-3-15
描述：ReidsHelper
"""

import asyncio_redis

from setting import REDIS_HOST, REDIS_PORT, REDIS_PWD


class ReidsHelper:
    def __init__(self):
        self._connection = None

    async def _get_connection(self):
        """获取连接"""
        if self._connection is None:
            self._connection = await asyncio_redis.Connection.create(host=REDIS_HOST, port=REDIS_PORT, password=REDIS_PWD)

    async def set(self, key, value):
        await self._get_connection()
        result = await self._connection.set(key, value)
        return result.status == 'OK'

    async def get(self, key):
        await self._get_connection()
        result = await self._connection.get(key)
        return result

    async def delete(self, key_or_keys):
        await self._get_connection()

        if isinstance(key_or_keys, str):
            key_or_keys = [key_or_keys]
        await self._connection.delete(key_or_keys)

    async def append(self, key, value):
        await self._connection.rpush(key, value)

    def close(self):
        try:
            if self._connection is not None:
                self._connection.close()
        except Exception as e:
            print('redis-helper.close()', e)


if __name__ == '__main__':
    from tornado.ioloop import IOLoop
    from tornado.gen import coroutine


    @coroutine
    def tor_run():
        cache = ReidsHelper()
        try:
            result = yield cache.set('my_key', '123')
            print('set.result=>', result)

            result = yield cache.get('my_key')
            print('get . result=>', result)

            result = yield cache.get('other_key')
            print('get . result=>', result)

            result = yield cache.set('my_key', '123')
            print('set.result=>', result)

            result = yield cache.delete(['my_key'])
            print('set.result=>', result)



        finally:
            cache.close()


    IOLoop.current().run_sync(tor_run)
